package com.authine.cloudpivot.ext.applicationservice;

import com.alibaba.cola.dto.SingleResponse;
import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.ext.applicationservice.base.ApplicationBaseService;
import com.authine.cloudpivot.ext.constants.ModelConst;
import com.authine.cloudpivot.ext.dto.OrderCustomerDto;
import com.authine.cloudpivot.ext.dto.OrderCustomerGoodsDto;
import com.authine.cloudpivot.ext.dto.OrderGoodsReturnsDto;
import com.authine.cloudpivot.ext.dto.api.AgreeRefundVO;
import com.authine.cloudpivot.ext.dto.transfer.PurchaseOrderReturnDto;
import com.authine.cloudpivot.ext.enums.order.OrderGoodsReturnsStatusEnum;
import com.authine.cloudpivot.ext.service.OrderService;
import com.authine.cloudpivot.ext.service.TransferOrderService;
import com.authine.cloudpivot.ext.service.impl.OrderServiceImpl;
import com.authine.cloudpivot.ext.service.impl.TransferOrderServiceImpl;
import com.authine.cloudpivot.ext.utils.BoResultFormat;
import com.authine.cloudpivot.ext.utils.JdbcTemplateUtils;
import com.authine.cloudpivot.ext.utils.StringUtils;
import com.authine.common.json.JsonUtils;
import com.authine.mvp.app.launcher.domain.utills.ApplicationContextUtils;
import com.authine.mvp.app.launcher.dto.bo.response.BO;
import com.authine.mvp.app.launcher.dto.bo.response.BOList;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.util.CollectionUtils;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.authine.hermes.app.launcher.service.ApplicationServiceFoundation.CUSTOM_SERVICE;

/**
 * @ClassName OrderReturnGoodsService
 * @Description: 售后退款自定义服务
 * @Author cjj
 * @Date 2021/4/20
 * @Version V1.0
 **/
@Path("OrderReturnGoodsService")
@Slf4j
public class OrderReturnGoodsService extends ApplicationBaseService {
    private NamedParameterJdbcTemplate jdbcTemplate = ApplicationContextUtils.getBean(NamedParameterJdbcTemplate.class);
    private OrderService orderService = new OrderServiceImpl();
    private TransferOrderService transferOrderService = new TransferOrderServiceImpl();

    /**
     * 退款申请
     *
     * @param dto
     * @return
     */
    @Path("refundApply")
    @POST
    @Operation(summary = "售后退款-待审批-退款审批", tags = CUSTOM_SERVICE, description = "orderGoodsIds必填")
    public SingleResponse refundApply(@Parameter AgreeRefundVO dto) {
        log.info("------------------------售后退款-待审批-退款审批 refundApply Param：{}------------------------", JSONObject.toJSONString(dto));
        if (CollectionUtils.isEmpty(dto.getOrderGoodsIds())) {
            return SingleResponse.buildFailure("-1", "订单商品ID集合必填");
        }
        //平台审批
        dto.setType("1");
        SingleResponse result = orderService.approvalRefund(dto);
        log.info("------------------------售后退款-待审批-退款审批 refundApply Result：{}------------------------", JSONObject.toJSONString(result));
        return result;
    }

    /**
     * 退款订单列表
     *
     * @param dto
     * @return
     */
    @Path("returnOrderList")
    @POST
    @Operation(summary = "售后退款-退款订单列表", tags = CUSTOM_SERVICE, description = "pageIndex、pageSize必填")
    public SingleResponse<BOList> returnOrderList(@Parameter OrderCustomerDto dto) {
        log.info("------------------------售后退款-退款订单列表 returnOrderList Param：{}------------------------", JSONObject.toJSONString(dto));
        if (null == dto.getPageIndex() || null == dto.getPageSize()) {
            return SingleResponse.buildFailure("-1", "pageIndex、pageSize必填");
        }
        String tableName = getTableName(ModelConst.T_ORDER_CUSTOMER);
        Map<String, Object> parameter = new HashMap<>();
        StringBuilder listSql = new StringBuilder();
        StringBuilder whereSql = new StringBuilder();
        StringBuilder countSql = new StringBuilder();
        listSql.append("select * from " + tableName + " where deleted ='0' and after_sale<>'未售后' ");
        countSql.append("select count(*) from " + tableName + " where deleted ='0' and after_sale<>'未售后' ");
        //拼接参数
        if (StringUtils.isNotBlank(dto.getId())) {
            List<String> ids = StringUtils.stringToListString(dto.getId(), ";");
            whereSql.append(" and id in (:id) ");
            parameter.put("id", ids);
        }
        if (StringUtils.isNotBlank(dto.getPlaceOrderFullname())) {
            whereSql.append(" and place_order_fullname like :placeOrderFullname ");
            parameter.put("placeOrderFullname", "%" + dto.getPlaceOrderFullname() + "%");
        }
        if (StringUtils.isNotBlank(dto.getOrganizationName())) {
            whereSql.append("and organization_name like :organizationName ");
            parameter.put("organizationName", "%" + dto.getOrganizationName() + "%");
        }
        if (StringUtils.isNotBlank(dto.getReceiver())) {
            whereSql.append(" and receiver like :receiver ");
            parameter.put("receiver", "%" + dto.getReceiver() + "%");
        }
        if (StringUtils.isNotBlank(dto.getPhone())) {
            whereSql.append(" and phone like :phone ");
            parameter.put("phone", "%" + dto.getPhone() + "%");
        }
        if (StringUtils.isNotBlank(dto.getPostal())) {
            whereSql.append(" and postal like :postal ");
            parameter.put("postal", "%" + dto.getPostal() + "%");
        }
        if (StringUtils.isNotBlank(dto.getAddress())) {
            whereSql.append(" and address like :address ");
            parameter.put("address", "%" + dto.getAddress() + "%");
        }
        if (StringUtils.isNotBlank(dto.getStartTime()) && StringUtils.isNotBlank(dto.getEndTime())) {
            whereSql.append(" and place_order_time between :startTime and :endTime ");
            parameter.put("startTime", dto.getStartTime());
            parameter.put("endTime", dto.getEndTime());
        }
        countSql.append(whereSql);
        listSql.append(whereSql);
        listSql.append(" order by createdTime desc");
        listSql.append(" limit " + dto.getPageIndex() * dto.getPageSize() + ", " + dto.getPageSize());
        log.info("------------------------售后退款-退款订单列表 returnOrderList listSql：{}------------------------parameter：{}", listSql, JsonUtils.toJson(parameter));
        log.info("------------------------售后退款-退款订单列表 returnOrderList whereSql：{}------------------------parameter：{}", whereSql, listSql, JsonUtils.toJson(parameter));
        List<Map<String, Object>> resultList = jdbcTemplate.queryForList(listSql.toString(), parameter);
        Integer count = 0;
        try {
            count = jdbcTemplate.queryForObject(countSql.toString(), parameter, Integer.class);
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
        //构建结果集
        BoResultFormat.resultFormat(resultList, ModelConst.T_ORDER_CUSTOMER);
        BOList bOList = new BOList();
        bOList.setData(resultList);
        bOList.setTotal(count);
        bOList.setSchemaCode(ModelConst.T_ORDER_CUSTOMER);
        return SingleResponse.of(bOList);
    }

    /**
     * 退款订单商品列表
     *
     * @param dto
     * @return
     */
    @Path("returnGoodsList")
    @POST
    @Operation(summary = "售后退款-退款订单商品列表", tags = CUSTOM_SERVICE, description = "pageIndex、pageSize必填")
    public SingleResponse<BOList> returnGoodsList(@Parameter OrderCustomerGoodsDto dto) {
        log.info("------------------------售后退款-退款订单商品列表 returnGoodsList Param：{}------------------------", JSONObject.toJSONString(dto));
        if (null == dto.getPageIndex() || null == dto.getPageSize()) {
            return SingleResponse.buildFailure("-1", "pageIndex、pageSize必填");
        }
        String goodsTableName = getTableName(ModelConst.T_ORDER_CUSTOMER_GOODS);
        String customerTableName = getTableName(ModelConst.T_ORDER_CUSTOMER);
        Map<String, Object> parameter = new HashMap<>();
        StringBuilder listSql = new StringBuilder();
        StringBuilder whereSql = new StringBuilder();
        StringBuilder countSql = new StringBuilder();
        listSql.append("select ocg.* from " + goodsTableName + " ocg " +
                "LEFT JOIN " + customerTableName + " oc on oc.id = ocg.order_customer_id " +
                "where ocg.deleted ='0' and oc.deleted ='0' and oc.after_sale<>'未售后' ");
        countSql.append("select count(*) from " + goodsTableName + " ocg " +
                "LEFT JOIN " + customerTableName + " oc on oc.id = ocg.order_customer_id " +
                "where ocg.deleted ='0' and oc.deleted ='0' and oc.after_sale<>'未售后' ");
        //拼接参数
        //客户订单商品序号
        if (StringUtils.isNotBlank(dto.getId())) {
            List<String> ids = StringUtils.stringToListString(dto.getId(), ";");
            whereSql.append(" and ocg.id in (:id) ");
            parameter.put("id", ids);
        }
        //客户订单序号
        if (StringUtils.isNotBlank(dto.getOrderCustomerId())) {
            List<String> orderCustomerIds = StringUtils.stringToListString(dto.getOrderCustomerId(), ";");
            whereSql.append(" and ocg.order_customer_id in (:order_customer_id) ");
            parameter.put("order_customer_id", orderCustomerIds);
        }
        //供应商订单序号
        if (StringUtils.isNotBlank(dto.getOrderVendorId())) {
            List<String> orderVendorIds = StringUtils.stringToListString(dto.getOrderVendorId(), ";");
            whereSql.append(" and ocg.order_vendor_id in (:order_vendor_id) ");
            parameter.put("order_vendor_id", orderVendorIds);
        }
        //客户名称
        if (StringUtils.isNotBlank(dto.getCustomerOrganizationName())) {
            whereSql.append(" and ocg.customer_organization_name like :customer_organization_name ");
            parameter.put("customer_organization_name", "%" + dto.getCustomerOrganizationName() + "%");
        }
        //供应商名称
        if (StringUtils.isNotBlank(dto.getVendorOrganizationName())) {
            whereSql.append(" and ocg.vendor_organization_name like :vendor_organization_name ");
            parameter.put("vendor_organization_name", "%" + dto.getVendorOrganizationName() + "%");
        }
        //商品状态
        if (null != dto.getOrderCustomerGoodsStatus()) {
            whereSql.append(" and ocg.order_customer_goods_status =:status ");
            parameter.put("status", dto.getOrderCustomerGoodsStatus());
        }
        //下单日期
        if (StringUtils.isNotBlank(dto.getStartTime()) && StringUtils.isNotBlank(dto.getEndTime())) {
            whereSql.append(" and ocg.place_order_time between :startTime and :endTime ");
            parameter.put("startTime", dto.getStartTime());
            parameter.put("endTime", dto.getEndTime());
        }
        countSql.append(whereSql);
        listSql.append(whereSql);
        listSql.append(" order by ocg.createdTime desc");
        listSql.append(" limit " + dto.getPageIndex() * dto.getPageSize() + ", " + dto.getPageSize());
        log.info("------------------------售后退款-退款订单商品列表 returnGoodsList listSql：{}------------------------parameter：{}", listSql, JsonUtils.toJson(parameter));
        List<Map<String, Object>> resultList = jdbcTemplate.queryForList(listSql.toString(), parameter);
        Integer count = 0;
        try {
            count = jdbcTemplate.queryForObject(countSql.toString(), parameter, Integer.class);
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
        //构建结果集
        BoResultFormat.resultFormat(resultList, ModelConst.T_ORDER_CUSTOMER_GOODS);
        BOList bOList = new BOList();
        bOList.setData(resultList);
        bOList.setTotal(count);
        bOList.setSchemaCode(ModelConst.T_ORDER_CUSTOMER_GOODS);
        return SingleResponse.of(bOList);
    }

    /**
     * 待审批
     *
     * @param dto
     * @return
     */
    @Path("auditingList")
    @POST
    @Operation(summary = "售后退款-待审批列表", tags = CUSTOM_SERVICE, description = "pageIndex、pageSize必填")
    public SingleResponse<BOList> auditingList(@Parameter OrderGoodsReturnsDto dto) {
        log.info("------------------------售后退款-退货中列表 auditingList Param：{}------------------------", JSONObject.toJSONString(dto));
        if (null == dto.getPageIndex() || null == dto.getPageSize()) {
            return SingleResponse.buildFailure("-1", "pageIndex、pageSize必填");
        }
        String tableName = getTableName(ModelConst.T_ORDER_GOODS_RETURNS);
        String ocTableName = getTableName(ModelConst.T_ORDER_CUSTOMER);
        String ocgTableName = getTableName(ModelConst.T_ORDER_CUSTOMER_GOODS);
        Map<String, Object> parameter = new HashMap<>();
        StringBuilder listSql = new StringBuilder();
        StringBuilder whereSql = new StringBuilder();
        StringBuilder countSql = new StringBuilder();
        listSql.append("select * from " + tableName + " ogr " +
                "left join " + ocTableName + " oc on ogr.order_customer_id = oc.id " +
                "left join " + ocgTableName + " ocg on ogr.order_customer_goods_id = ocg.id " +
                "where ogr.deleted ='0' and ogr.order_goods_returns_status in ('"+ OrderGoodsReturnsStatusEnum.PendingMiddlemanConfirm+"') ");
        countSql.append("select count(*) from " + tableName + " ogr " +
                "left join " + ocTableName + " oc on ogr.order_customer_id = oc.id " +
                "left join " + ocgTableName + " ocg on ogr.order_customer_goods_id = ocg.id " +
                "where ogr.deleted ='0' and ogr.order_goods_returns_status in ('"+ OrderGoodsReturnsStatusEnum.PendingMiddlemanConfirm+"') ");
        //拼接参数
        //客户订单商品序号
        if (StringUtils.isNotBlank(dto.getOrderCustomerGoodsId())) {
            List<String> orderCustomerGoodsIds = StringUtils.stringToListString(dto.getOrderCustomerGoodsId(), ";");
            whereSql.append(" and ogr.order_customer_goods_id in (:order_customer_goods_id) ");
            parameter.put("order_customer_goods_id", orderCustomerGoodsIds);
        }
        //客户订单序号
        if (StringUtils.isNotBlank(dto.getOrderCustomerId())) {
            List<String> orderCustomerIds = StringUtils.stringToListString(dto.getOrderCustomerId(), ";");
            whereSql.append(" and ogr.order_customer_id in (:order_customer_id) ");
            parameter.put("order_customer_id", orderCustomerIds);
        }
        //供应商订单序号
        if (StringUtils.isNotBlank(dto.getOrderVendorId())) {
            List<String> orderVendorIds = StringUtils.stringToListString(dto.getOrderVendorId(), ";");
            whereSql.append(" and ogr.order_vendor_id in (:order_vendor_id) ");
            parameter.put("order_vendor_id", orderVendorIds);
        }
        //下单组织
        if (StringUtils.isNotBlank(dto.getOrganizationName())) {
            whereSql.append("and oc.organization_name like :organizationName ");
            parameter.put("organizationName", "%" + dto.getOrganizationName() + "%");
        }
        //品牌
        if (StringUtils.isNotBlank(dto.getBrand())) {
            whereSql.append("and ocg.brand like :brand ");
            parameter.put("brand", "%" + dto.getBrand() + "%");
        }
        //商品名称
        if (StringUtils.isNotBlank(dto.getName())) {
            whereSql.append("and ocg.name like :name ");
            parameter.put("name", "%" + dto.getName() + "%");
        }
        //型号
        if (StringUtils.isNotBlank(dto.getModel())) {
            whereSql.append("and ocg.model like :model ");
            parameter.put("model", "%" + dto.getModel() + "%");
        }
        //规格
        if (StringUtils.isNotBlank(dto.getSpec())) {
            whereSql.append("and ocg.spec like :spec ");
            parameter.put("spec", "%" + dto.getSpec() + "%");
        }
        countSql.append(whereSql);
        listSql.append(whereSql);
        listSql.append(" order by ogr.createdTime desc");
        listSql.append(" limit " + dto.getPageIndex() * dto.getPageSize() + ", " + dto.getPageSize());
        log.info("------------------------售后退款-退货中列表 returnList listSql：{}------------------------parameter：{}", listSql, JsonUtils.toJson(parameter));
        List<Map<String, Object>> resultList = jdbcTemplate.queryForList(listSql.toString(), parameter);
        Integer count = 0;
        try {
            count = jdbcTemplate.queryForObject(countSql.toString(), parameter, Integer.class);
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
        for (Map<String, Object> objectMap : resultList) {
            // 数量求和
            BigDecimal number = new BigDecimal("0.00");
            List<PurchaseOrderReturnDto> purchaseOrderReturnModel = transferOrderService.getPurchaseReturnInfo((String)objectMap.get("order_customer_goods_id"));
            for (PurchaseOrderReturnDto orderReturnModel : purchaseOrderReturnModel) {
                number = orderReturnModel.getNum().add(number);
            }
            //设置退款数量
            objectMap.put("purchase_order_return_num", number);
        }
        //构建结果集
        BoResultFormat.resultFormat(resultList, ModelConst.T_ORDER_GOODS_RETURNS);
        BOList bOList = new BOList();
        bOList.setData(resultList);
        bOList.setTotal(count);
        bOList.setSchemaCode(ModelConst.T_ORDER_GOODS_RETURNS);
        return SingleResponse.of(bOList);
    }


    /**
     * 待确认入库
     *
     * @param dto
     * @return
     */
    @Path("confirmedList")
    @POST
    @Operation(summary = "售后退款-待确认入库列表", tags = CUSTOM_SERVICE, description = "pageIndex、pageSize必填")
    public SingleResponse<BOList> confirmedList(@Parameter OrderGoodsReturnsDto dto) {
        log.info("------------------------售后退款-退款订单商品列表 confirmedList Param：{}------------------------", JSONObject.toJSONString(dto));
        if (null == dto.getPageIndex() || null == dto.getPageSize()) {
            return SingleResponse.buildFailure("-1", "pageIndex、pageSize必填");
        }
        String tableName = getTableName(ModelConst.T_ORDER_GOODS_RETURNS);
        Map<String, Object> parameter = new HashMap<>();
        StringBuilder listSql = new StringBuilder();
        StringBuilder whereSql = new StringBuilder();
        StringBuilder countSql = new StringBuilder();
        listSql.append("select * from " + tableName + " where deleted ='0' and order_goods_returns_status ='ReturnedDoneDelivery' and is_to_pm=true ");
        countSql.append("select count(*) from " + tableName + " where deleted ='0' and order_goods_returns_status ='ReturnedDoneDelivery' and is_to_pm=true ");
        //拼接参数
        //客户订单商品序号
        if (StringUtils.isNotBlank(dto.getOrderCustomerGoodsId())) {
            List<String> orderCustomerGoodsIds = StringUtils.stringToListString(dto.getOrderCustomerGoodsId(), ";");
            whereSql.append(" and order_customer_goods_id in (:order_customer_goods_id) ");
            parameter.put("order_customer_goods_id", orderCustomerGoodsIds);
        }
        //客户订单序号
        if (StringUtils.isNotBlank(dto.getOrderCustomerId())) {
            List<String> orderCustomerIds = StringUtils.stringToListString(dto.getOrderCustomerId(), ";");
            whereSql.append(" and order_customer_id in (:order_customer_id) ");
            parameter.put("order_customer_id", orderCustomerIds);
        }
        //供应商订单序号
        if (StringUtils.isNotBlank(dto.getOrderVendorGoodsId())) {
            List<String> orderVendorGoodsIds = StringUtils.stringToListString(dto.getOrderVendorGoodsId(), ";");
            whereSql.append(" and order_vendor_goods_id in (:order_vendor_goods_id) ");
            parameter.put("order_vendor_goods_id", orderVendorGoodsIds);
        }
        //客户名称
        if (StringUtils.isNotBlank(dto.getCustomerOrganizationName())) {
            whereSql.append(" and customer_organization_name like :customer_organization_name ");
            parameter.put("customer_organization_name", "%" + dto.getCustomerOrganizationName() + "%");
        }
        //供应商名称
        if (StringUtils.isNotBlank(dto.getVendorOrganizationName())) {
            whereSql.append(" and vendor_organization_name like :vendor_organization_name ");
            parameter.put("vendor_organization_name", "%" + dto.getVendorOrganizationName() + "%");
        }
        countSql.append(whereSql);
        listSql.append(whereSql);
        listSql.append(" order by createdTime desc");
        listSql.append(" limit " + dto.getPageIndex() * dto.getPageSize() + ", " + dto.getPageSize());
        log.info("------------------------售后退款-退款订单商品列表 confirmedList listSql：{}------------------------parameter：{}", listSql, JsonUtils.toJson(parameter));
        log.info("------------------------售后退款-退款订单商品列表 confirmedList whereSql：{}------------------------parameter：{}", whereSql, listSql, JsonUtils.toJson(parameter));
        List<Map<String, Object>> resultList = jdbcTemplate.queryForList(listSql.toString(), parameter);
        Integer count = 0;
        try {
            count = jdbcTemplate.queryForObject(countSql.toString(), parameter, Integer.class);
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
        //构建结果集
        BoResultFormat.resultFormat(resultList, ModelConst.T_ORDER_GOODS_RETURNS);
        BOList bOList = new BOList();
        bOList.setData(resultList);
        bOList.setTotal(count);
        bOList.setSchemaCode(ModelConst.T_ORDER_GOODS_RETURNS);
        return SingleResponse.of(bOList);
    }

    /**
     * 批量确认已收到退货商品
     *
     * @param dto
     * @return
     */
    @Path("confirmReturnedGoods")
    @POST
    @Operation(summary = "售后退款-待确认入库-确认", tags = CUSTOM_SERVICE, description = "ids必填")
    public SingleResponse<BO> confirmReturnedGoods(@Parameter OrderCustomerGoodsDto dto) {
        log.info("------------------------售后退款-待确认入库-确认 refundApply Param：{}------------------------", JSONObject.toJSONString(dto));
        if (CollectionUtils.isEmpty(dto.getIds())) {
            return SingleResponse.buildFailure("-1", "客户订单商品ID集合必填");
        }
        return orderService.confireReturn(dto.getIds());
    }

    /**
     * 退货中
     *
     * @param dto
     * @return
     */
    @Path("returnList")
    @POST
    @Operation(summary = "售后退款-退货中列表", tags = CUSTOM_SERVICE, description = "pageIndex、pageSize必填")
    public SingleResponse<BOList> returnList(@Parameter OrderGoodsReturnsDto dto) {
        log.info("------------------------售后退款-退货中列表 returnList Param：{}------------------------", JSONObject.toJSONString(dto));
        if (null == dto.getPageIndex() || null == dto.getPageSize()) {
            return SingleResponse.buildFailure("-1", "pageIndex、pageSize必填");
        }
        String tableName = getTableName(ModelConst.T_ORDER_GOODS_RETURNS);
        Map<String, Object> parameter = new HashMap<>();
        StringBuilder listSql = new StringBuilder();
        StringBuilder whereSql = new StringBuilder();
        StringBuilder countSql = new StringBuilder();
        listSql.append("select * from " + tableName + " where deleted ='0' and order_goods_returns_status in ('"+ OrderGoodsReturnsStatusEnum.ReturnPending+"') ");
        countSql.append("select count(*) from " + tableName + " where deleted ='0' and order_goods_returns_status in ('"+ OrderGoodsReturnsStatusEnum.ReturnPending+"') ");
        //拼接参数
        //客户订单商品序号
        if (StringUtils.isNotBlank(dto.getOrderCustomerGoodsId())) {
            List<String> orderCustomerGoodsIds = StringUtils.stringToListString(dto.getOrderCustomerGoodsId(), ";");
            whereSql.append(" and order_customer_goods_id in (:order_customer_goods_id) ");
            parameter.put("order_customer_goods_id", orderCustomerGoodsIds);
        }
        //客户订单序号
        if (StringUtils.isNotBlank(dto.getOrderCustomerId())) {
            List<String> orderCustomerIds = StringUtils.stringToListString(dto.getOrderCustomerId(), ";");
            whereSql.append(" and order_customer_id in (:order_customer_id) ");
            parameter.put("order_customer_id", orderCustomerIds);
        }
        //供应商订单序号
        if (StringUtils.isNotBlank(dto.getOrderVendorId())) {
            List<String> orderVendorIds = StringUtils.stringToListString(dto.getOrderVendorId(), ";");
            whereSql.append(" and order_vendor_id in (:order_vendor_id) ");
            parameter.put("order_vendor_id", orderVendorIds);
        }
        //客户名称
        if (StringUtils.isNotBlank(dto.getCustomerOrganizationName())) {
            whereSql.append(" and customer_organization_name like :customer_organization_name ");
            parameter.put("customer_organization_name", "%" + dto.getCustomerOrganizationName() + "%");
        }
        //供应商名称
        if (StringUtils.isNotBlank(dto.getVendorOrganizationName())) {
            whereSql.append(" and vendor_organization_name like :vendor_organization_name ");
            parameter.put("vendor_organization_name", "%" + dto.getVendorOrganizationName() + "%");
        }
        countSql.append(whereSql);
        listSql.append(whereSql);
        listSql.append(" order by createdTime desc");
        listSql.append(" limit " + dto.getPageIndex() * dto.getPageSize() + ", " + dto.getPageSize());
        log.info("------------------------售后退款-退货中列表 returnList listSql：{}------------------------parameter：{}", listSql, JsonUtils.toJson(parameter));
        List<Map<String, Object>> resultList = jdbcTemplate.queryForList(listSql.toString(), parameter);
        Integer count = 0;
        try {
            count = jdbcTemplate.queryForObject(countSql.toString(), parameter, Integer.class);
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
        for (Map<String, Object> objectMap : resultList) {
            // 数量求和
            BigDecimal number = new BigDecimal("0.00");
            List<PurchaseOrderReturnDto> purchaseOrderReturnModel = transferOrderService.getPurchaseReturnInfo((String)objectMap.get("order_customer_goods_id"));
            for (PurchaseOrderReturnDto orderReturnModel : purchaseOrderReturnModel) {
                number = orderReturnModel.getNum().add(number);
            }
            //设置退款数量
            objectMap.put("purchase_order_return_num", number);
            //设置可退数量
            objectMap.put("quantity_returnable", getRefundableNum((String)objectMap.get("order_customer_goods_id")));
        }
        //构建结果集
        BoResultFormat.resultFormat(resultList, ModelConst.T_ORDER_GOODS_RETURNS);
        BOList bOList = new BOList();
        bOList.setData(resultList);
        bOList.setTotal(count);
        bOList.setSchemaCode(ModelConst.T_ORDER_GOODS_RETURNS);
        return SingleResponse.of(bOList);
    }

    /**
     * 修改退款单信息
     *
     * @param dto
     * @return
     */
    @Path("editReturnedGoods")
    @POST
    @Operation(summary = "售后退款-退货中-提交修改退款单信息", tags = CUSTOM_SERVICE, description = "orderCustomerGoodsId、customerAmount、quantity必填，memo选填")
    public SingleResponse<BO> editReturnedGoods(@Parameter OrderGoodsReturnsDto dto) {
        log.info("------------------------售后退款-退货中-提交修改退款单信息 editReturnedGoods Param：{}------------------------", JSONObject.toJSONString(dto));
        if (StringUtils.isBlank(dto.getId()) || null == dto.getCustomerAmount() || null == dto.getQuantity()) {
            return SingleResponse.buildFailure("-1", "参数不合法");
        }
        return orderService.editRefund(dto.getId(), dto.getCustomerAmount(), dto.getQuantity(), dto.getMemo());
    }

    /**
     * 批量带财务确认
     *
     * @param dto
     * @return
     */
    @Path("confirmFinance")
    @POST
    @Operation(summary = "售后退款-带财务确认-确认", tags = CUSTOM_SERVICE, description = "ids必填")
    public SingleResponse confirmFinance(@Parameter OrderGoodsReturnsDto dto) {
        log.info("------------------------售后退款-带财务确认-确认 confirmFinance Param：{}------------------------", JSONObject.toJSONString(dto));
        if (CollectionUtils.isEmpty(dto.getIds())) {
            return SingleResponse.buildFailure("-1", "订单商品退货ID集合必填");
        }
        return SingleResponse.of(orderService.refundFinanceConfirm(dto.getIds()));
    }

    /**
     * 售后退款-待财务确认列表
     *
     * @param dto
     * @return
     */
    @Path("financeConfirmList")
    @POST
    @Operation(summary = "售后退款-退货中列表", tags = CUSTOM_SERVICE, description = "pageIndex、pageSize必填")
    public SingleResponse<BOList> financeConfirmList(@Parameter OrderGoodsReturnsDto dto) {
        log.info("------------------------售后退款-待财务确认列表 financeConfirmList Param：{}------------------------", JSONObject.toJSONString(dto));
        if (null == dto.getPageIndex() || null == dto.getPageSize()) {
            return SingleResponse.buildFailure("-1", "pageIndex、pageSize必填");
        }
        String tableName = getTableName(ModelConst.T_ORDER_GOODS_RETURNS);
        Map<String, Object> parameter = new HashMap<>();
        StringBuilder listSql = new StringBuilder();
        StringBuilder whereSql = new StringBuilder();
        StringBuilder countSql = new StringBuilder();
        listSql.append("select * from " + tableName + " where deleted ='0' and order_goods_returns_status in ('"+ OrderGoodsReturnsStatusEnum.PendingFinanceConfirm+"') ");
        countSql.append("select count(*) from " + tableName + " where deleted ='0' and order_goods_returns_status in ('"+ OrderGoodsReturnsStatusEnum.PendingFinanceConfirm+"') ");
        //拼接参数
        //客户订单商品序号
        if (StringUtils.isNotBlank(dto.getOrderCustomerGoodsId())) {
            List<String> orderCustomerGoodsIds = StringUtils.stringToListString(dto.getOrderCustomerGoodsId(), ";");
            whereSql.append(" and order_customer_goods_id in (:order_customer_goods_id) ");
            parameter.put("order_customer_goods_id", orderCustomerGoodsIds);
        }
        //客户订单序号
        if (StringUtils.isNotBlank(dto.getOrderCustomerId())) {
            List<String> orderCustomerIds = StringUtils.stringToListString(dto.getOrderCustomerId(), ";");
            whereSql.append(" and order_customer_id in (:order_customer_id) ");
            parameter.put("order_customer_id", orderCustomerIds);
        }
        //供应商订单序号
        if (StringUtils.isNotBlank(dto.getOrderVendorId())) {
            List<String> orderVendorIds = StringUtils.stringToListString(dto.getOrderVendorId(), ";");
            whereSql.append(" and order_vendor_id in (:order_vendor_id) ");
            parameter.put("order_vendor_id", orderVendorIds);
        }
        //下单组织
        if (StringUtils.isNotBlank(dto.getOrganizationName())) {
            whereSql.append("and organization_name like :organizationName ");
            parameter.put("organizationName", "%" + dto.getOrganizationName() + "%");
        }
        //平台组织名称
        if (StringUtils.isNotBlank(dto.getPlatformId())) {
            whereSql.append(" and JSON_UNQUOTE(platform_id ->'$.id') = :platformId");
            parameter.put("platformId", dto.getPlatformId());
        }
        //品牌
        if (StringUtils.isNotBlank(dto.getBrand())) {
            whereSql.append("and brand like :brand ");
            parameter.put("brand", "%" + dto.getBrand() + "%");
        }
        //商品名称
        if (StringUtils.isNotBlank(dto.getName())) {
            whereSql.append("and name like :name ");
            parameter.put("name", "%" + dto.getName() + "%");
        }
        //型号
        if (StringUtils.isNotBlank(dto.getModel())) {
            whereSql.append("and model like :model ");
            parameter.put("model", "%" + dto.getModel() + "%");
        }
        //规格
        if (StringUtils.isNotBlank(dto.getSpec())) {
            whereSql.append("and spec like :spec ");
            parameter.put("spec", "%" + dto.getSpec() + "%");
        }
        countSql.append(whereSql);
        listSql.append(whereSql);
        listSql.append(" order by createdTime desc");
        listSql.append(" limit " + dto.getPageIndex() * dto.getPageSize() + ", " + dto.getPageSize());
        log.info("------------------------售后退款-待财务确认列表 financeConfirmList listSql：{}------------------------parameter：{}", listSql, JsonUtils.toJson(parameter));
        List<Map<String, Object>> resultList = jdbcTemplate.queryForList(listSql.toString(), parameter);
        Integer count = 0;
        try {
            count = jdbcTemplate.queryForObject(countSql.toString(), parameter, Integer.class);
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
        for (Map<String, Object> objectMap : resultList) {
            List<PurchaseOrderReturnDto> purchaseOrderReturnModel = transferOrderService.getPurchaseReturnInfo((String)objectMap.get("order_customer_goods_id"));
            if (null != purchaseOrderReturnModel && !purchaseOrderReturnModel.isEmpty()){
                objectMap.put("vendor_name",null == purchaseOrderReturnModel.get(0).getVendorName() ? null :purchaseOrderReturnModel.get(0).getVendorName().substring(0,purchaseOrderReturnModel.get(0).getVendorName().length()-1));
                objectMap.put("rp_code",null == purchaseOrderReturnModel.get(0).getRpCode() ? null :purchaseOrderReturnModel.get(0).getRpCode().substring(0,purchaseOrderReturnModel.get(0).getRpCode().length()-1));
                objectMap.put("rp_time",null == purchaseOrderReturnModel.get(0).getRpTime() ? null :purchaseOrderReturnModel.get(0).getRpTime().substring(0,purchaseOrderReturnModel.get(0).getRpTime().length()-1));
            }
        }
        //构建结果集
        BoResultFormat.resultFormat(resultList, ModelConst.T_ORDER_GOODS_RETURNS);
        BOList bOList = new BOList();
        bOList.setData(resultList);
        bOList.setTotal(count);
        bOList.setSchemaCode(ModelConst.T_ORDER_GOODS_RETURNS);
        return SingleResponse.of(bOList);
    }
}
